
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:nordic_otas_plugin/rtk_status.dart';
import 'package:nordic_otas_plugin_example/util/ble_sdk.dart';
import 'package:nordic_otas_plugin_example/util/device_key.dart';
import 'package:nordic_otas_plugin_example/util/event_bus.dart';
import 'package:path_provider/path_provider.dart';
// import 'package:rtk_ota_plugin/rtk_ota_plugin.dart';
// import 'package:rtk_ota_plugin/rtk_status.dart';
import 'package:nordic_otas_plugin/nordic_otas_plugin.dart';
import 'package:nordic_otas_plugin_example/util/app_all_value.dart';
import 'package:nordic_otas_plugin_example/util/http_api.dart';

//固件升级页面
class OtaPage extends StatefulWidget {
  String? mac;
  String? name;
  OtaPage({this.mac,this.name});

  @override
  State<OtaPage> createState() => _OtaPageState();
}

class _OtaPageState extends State<OtaPage> {

  String fileNetWorkPath = "https://hkoss.jointcorp.cloud/res/firmware/2301b/J2301B_V050_4_20240106.zip";
  String filePath = "未下载";
  late String savePath;
  double _downloadRatio = 0.0;
  String _downloadIndicator = '0.00%';
  late CancelToken _token;
  bool _downloading = false;
  TextEditingController filePathController = TextEditingController();
  String framePath = "未选择";
  String uiPath = "未选择";
  String updateFirmwareTip = "";
  AppAllValueController controller = Get.find();
  //是否处于更新设备中
  bool isUpdate = false;
  //更新文件是否下载完成
  bool isDownFile = false;

  @override
  void initState() {
    getSavePath();
    super.initState();
    filePathController.text = fileNetWorkPath;
    controller.connectDevice();
    EventBus().on('dataCallBack', (arg) {
      // print('flutter-dataCallBack');
      controller.disConnectDevice();
    });
    NordicOtasPlugin().otaListener((type, progress){
      switch(type){
        case NordicStatus.STATUS_SEARCH_DEVICE_ING:
          setState(() {
            updateFirmwareTip = "查询设备中";
          });
          break;
        case NordicStatus.STATUS_SEARCH_DEVICE_SUCC:
          setState(() {
            updateFirmwareTip = "找到设备";
          });
          break;
        case NordicStatus.STATUS_UPDATE_ING:
          setState(() {
            updateFirmwareTip = "升级中 ${progress}%";
          });
          break;
        case NordicStatus.STATUS_UPDATE_SUCC:
          setState(() {
            updateFirmwareTip = "升级完成";
          });
          isUpdate = false;
          break;
        case NordicStatus.STATUS_UPDATE_ERROE:
          setState(() {
            updateFirmwareTip = "升级失败";
          });
          break;
        case NordicStatus.STATUS_DEVICE_DISCONNECT:
          setState(() {
            updateFirmwareTip = "设备断开";
          });
          isUpdate = false;
          break;
      }
    });
  }


  ///获取保存的路径
  void getSavePath(){
    getTemporaryDirectory()
        .then((tempDir) => {savePath = tempDir.path + 'update.zip'});
  }

  ///下载文件
  void _downloadFile() {
    if (_downloading == true) {
      return;
    }
    _token = CancelToken();
    _downloading = true;
    HttpApi().doDownload(filePathController.text, savePath, cancelToken: _token,
        progress: (int received, int total) {
          // 下载进度
          setState(() {
            _downloadRatio = (received / total);
            if (_downloadRatio == 1) {
              _downloading = false;
            }
            _downloadIndicator = (_downloadRatio * 100).toStringAsFixed(2) + '%';
            filePath = "下载进度: $_downloadIndicator";
            print("下载进度: $_downloadIndicator");
          });
        }, completion: () {
          // 下载成功
          _downloading = false;
          isDownFile = true;
          print("下载完成:");
          setState(() {
            filePath = savePath;
          });
          NordicOtasPlugin().setFilePath(savePath);
          // FlutterLoadingHud.showToast(message: "\"下载完成\"");
        }, failure: (error) {
          // 下载出错
          _downloading = false;
          setState(() {
            filePath = "下载出错";
          });
          print("下载出错:${error.toString()}");
          // FlutterLoadingHud.showToast(message: error.message);
        });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("固件升级".tr),
      ),
      body: Column(
        mainAxisSize: MainAxisSize.max,
        children: [
          buildFilePathWidget(),
          buildDownFile(),
          buildUpdateFirmwareFile(),
        ],
      ),
    );
  }

  Widget buildFilePathWidget(){
    return Container(
      margin: EdgeInsets.only(left: 10,right: 10),
      height: 100,
      child: Row(
        children: [
          Text('升级文件地址：'.tr),
          Expanded(child: TextField(
            controller: filePathController,
            decoration: InputDecoration(
                hintText: '请输入升级文件路径'.tr
            ),
            textAlign: TextAlign.center,
            maxLines: null,
            keyboardType: TextInputType.text,
            textInputAction: TextInputAction.done,
          ))
        ],
      ),
    );
  }

  Widget buildDownFile(){
    return Container(
      margin: const EdgeInsets.only(left: 10,right: 10),
      height: 80,
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: [
          Container(
            width: 100,
            margin: const EdgeInsets.only(right: 10),
            child: ElevatedButton(
              child: Text('下载文件'.tr),
              onPressed: () async {
                if(filePathController.text.isNotEmpty){
                  _downloadFile();
                }
              },
            ),
          ),
          Expanded(child: Text(filePath))
        ],
      ),
    );
  }


  Widget buildUpdateFirmwareFile(){
    return Container(
      margin: const EdgeInsets.only(left: 10,right: 10),
      height: 40,
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: [
          Container(
            width: 200,
            margin: const EdgeInsets.only(right: 10),
            child: ElevatedButton(
              child: Text('固件升级'.tr),
              onPressed: () async {
                if(isDownFile){
                  if(isUpdate){
                    controller.showContentDialog("正在更新中，请勿重复点击".tr);
                  }else{
                    update(savePath);
                  }
                }else{
                  controller.showContentDialog("更新文件未下载".tr);
                }
              },
            ),
          ),
          Expanded(child: Text(updateFirmwareTip))
        ],
      ),
    );
  }

  ///开始升级
  void update(String path) async{
    setState(() {
      updateFirmwareTip = "开始升级";
    });
    isUpdate = true;
    if(widget.name == "Dfu2301"){//升级过程失败，已经处于升级模式，直接断开设备然后开始更新
      controller.cancelAutoConnect();
      controller.disConnectDevice();
    }else{
      controller.writeData(BleSDK.enterOTA());
      controller.cancelAutoConnect();
    }
    //需要等待设备进入升级模式之后再进行更新
    Future.delayed(Duration(seconds: 4),(){
      startOta();
    });
  }
  void startOta(){
    if(Platform.isAndroid){
      Future.delayed(const Duration(seconds: 5),(){
        NordicOtasPlugin().startAndroidOta('Dfu2301',getMacAdd(widget.mac!));
      });
    }else{
      Future.delayed(const Duration(seconds: 1),(){
        NordicOtasPlugin().startOta();
      });

    }
  }

  String getMacAdd(String mac) {
    String firstBytes = mac.substring(0, 15);
    String lastByte = mac.substring(15);
    int vv = int.parse(lastByte,radix: 16)+1;
    return '${firstBytes}${vv.toRadixString(16).toUpperCase()}';
  }

}
